package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.AllSelection
import com.gitee.wsl.doc.prosemirror.state.selection.TextSelection
import com.gitee.wsl.doc.prosemirror.transform.ext.insert
import com.gitee.wsl.ext.base.ifValue

object CreateParagraphNear: Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val sel = state.selection
        val from = sel._from
        val to = sel._to
        if (sel is AllSelection || from.parent.inlineContent || to.parent.inlineContent) return false
        val type = defaultBlockAt(to.parent.contentMatchAt(to.indexAfter()))
        if (type == null || !type.isTextblock) return false
        if (dispatch!=null) {
            val temp = (from.parentOffset > 0 && to.index() < to.parent.childCount).ifValue(from , to)
            val side = temp.pos
            val tr = state.tr.insert(side, type.createAndFill()!!)
            tr.setSelection(TextSelection.create(tr.doc, side + 1))
            dispatch(tr.scrollIntoView())
        }
        return true
    }
}

/// If a block node is selected, create an empty paragraph before (if
/// it is its parent's first child) or after it.
val Command.Companion.createParagraphNear get() = CreateParagraphNear

